﻿using IdentityModel;
using IdentityModel.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SupDataSync.Common;
using SupDataSync.Model;
using System;
using System.Data;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using DataSyncCommon;

namespace SupDataSync.ChildForms
{
    /// <summary>
    /// 设置连接
    /// </summary>
    public partial class FrmSet : Form
    {
        static string addr = "http://39.108.103.154";//正式/测试环境地址
        public FrmSet()
        {
            InitializeComponent();
        }

        private void FrmSet_Load(object sender, EventArgs e)
        {
            this.tb_ClinetIP.Text = ConfigHelper.GetAppConfig("host") + "";
            this.tb_ClientPort.Text = ConfigHelper.GetAppConfig("port") + "";
            this.tb_ClientUser.Text = ConfigHelper.GetAppConfig("user") + "";
            this.tb_ClientPwd.Text = ConfigHelper.GetAppConfig("pwd") + "";
            this.tb_WebApiUrl.Text = ConfigHelper.GetAppConfig("webapi") + "";
            addr = ConfigHelper.GetAppConfig("auth");
            try
            {
                //var responseStr = HttpHelper.RequestGet(ConfigHelper.GetAppConfig("webapi") + ":5005/auth/Tenant/GetAllPmsCustomers");
                //Newtonsoft.Json.Linq.JArray ja = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(responseStr);

                //DataTable dt = new DataTable();
                //dt.Columns.Add("tenantid");
                //dt.Columns.Add("tenantname");

                //for (var i = 0; i < ja.Count; i++)
                //{
                //    var tmpObj = (Newtonsoft.Json.Linq.JObject)ja[i];
                //    var role_id = (string)tmpObj["tenantid"];
                //    var role_name = (string)tmpObj["tenantname"];

                //    DataRow dr = dt.NewRow();
                //    dr["tenantid"] = role_id;
                //    dr["tenantname"] = role_name;
                //    dt.Rows.Add(dr);
                //}
                //if (dt.Rows.Count > 0)
                //{
                //    this.cmbcompany.DataSource = dt;
                //    this.cmbcompany.DisplayMember = "tenantname";
                //    this.cmbcompany.ValueMember = "tenantid";
                //}
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "提示");
            }
        }

        /// <summary>
        /// 获取数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ConnTest_Click(object sender, EventArgs e)
        {
            this.cmb_DbName.DataSource = null;
            string clientIP = this.tb_ClinetIP.Text.Trim();
            string clientPort = this.tb_ClientPort.Text.Trim();
            string clientUser = this.tb_ClientUser.Text.Trim();
            string clientPwd = this.tb_ClientPwd.Text.Trim();

            try
            {
                var conStr = "Data Source='{0}';Port='{1}';User Id='{2}';Password='{3}';pooling=true;character set=utf8;";
                conStr = string.Format(conStr, clientIP, clientPort, clientUser, clientPwd);
                string sql = "SELECT SCHEMA_NAME AS DBNAME FROM INFORMATION_SCHEMA.SCHEMATA order by SCHEMA_NAME";
                DataSet ds = null;
                DbHelperMySql.ExecuteQueryByConnstr(conStr, sql, out ds);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    this.cmb_DbName.DataSource = ds.Tables[0];
                    this.cmb_DbName.DisplayMember = "DBNAME";
                    this.cmb_DbName.ValueMember = "DBNAME";
                    this.cmb_DbName.SelectedValue = ConfigHelper.GetAppConfig("dbname") + "";
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message + "[任何可用插件都不支持身份验证方法“缓存密码”。请检查数据库IP地址以及密码是否正确]", "提示");
            }
        }

        /// <summary>
        /// 保存连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Save_Click(object sender, EventArgs e)
        {
            if (tbCompany.Text.Trim() == "")
            {
                MessageBox.Show("请输入企业ID","提示");
                return;
            }
            //SysConfig.TenantId = Convert.ToInt32(tbCompany.Text.Trim());
            if (string.IsNullOrEmpty(tbCompany.Text.Trim()))
            {
                MessageBox.Show("请用企业管理员账号先登录获取企业", "提示");
                return;
            }
            string clientIP = this.tb_ClinetIP.Text.Trim();
            string clientPort = this.tb_ClientPort.Text.Trim();
            string clientUser = this.tb_ClientUser.Text.Trim();
            string clientPwd = this.tb_ClientPwd.Text.Trim();
            string dbName = this.cmb_DbName.SelectedValue + "";
            Add_type(dbName, clientIP, clientPort, clientUser, clientPwd);

            if (dbName == "")
            {
                MessageBox.Show("请先选择要连接的数据库！", "提示");
                return;
            }

            SaveClientInfo(clientIP, clientPort, dbName, clientUser, clientPwd);
            MessageBox.Show("保存成功！", "提示");
        }

        private void SaveClientInfo(string ip, string port, string dbname, string user, string pwd)
        {
            SysConfig.ClientIP = ip;
            SysConfig.ClientPort = port;
            SysConfig.ClientDbName = dbname;
            SysConfig.ClientUser = user;
            SysConfig.ClientPwd = pwd;


            var conStr = "Data Source='{0}';Port='{1}';User Id='{2}';Password='{3}';Database='{4}';pooling=true;character set=utf8;";
            SysConfig.ConnectionStr = string.Format(conStr, ip, port, user, pwd, dbname);
            var mdiForm = (FrmMain)this.MdiParent;
            mdiForm.toolStrip_Status.Text = "当前数据库：" + dbname;

            ConfigHelper.UpdateAppConfig("host", ip);
            ConfigHelper.UpdateAppConfig("port", port);
            ConfigHelper.UpdateAppConfig("dbname", dbname);
            ConfigHelper.UpdateAppConfig("user", user);
            ConfigHelper.UpdateAppConfig("pwd", pwd);
            if (!string.IsNullOrEmpty(tbCompany.Text)) {
                //SysConfig.TenantId = Convert.ToInt32(Convert.ToInt32(tbCompany.Text));
                //ConfigHelper.UpdateAppConfig("tenantid", tbCompany.Text);
            }
        }

        /// <summary>
        /// 服务端访问测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ApiTest_Click(object sender, EventArgs e)
        {
            try
            {
                var url = SysConfig.TestApiUrl;
                var reqjson = JsonConvert.SerializeObject("test");
                var responseStr = HttpHelper.WebRequestApi(url, reqjson, "POST");
                if (responseStr == "OK")
                {
                    MessageBox.Show("访问成功！", "提示");
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("访问失败：" + err.Message, "提示");
            }
        }
        /// <summary>
        /// 登陆权限认证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                var sync = RequestTokenAsync();
                //var call = CallServiceAsync(sync.Result.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        async Task<TokenResponse> RequestTokenAsync()
        {
            try
            {
                var client = new HttpClient();
                var disco = await client.GetDiscoveryDocumentAsync(
                    new DiscoveryDocumentRequest { Policy = { RequireHttps = false }, Address = addr + ":5004" }
                    );
                if (disco.IsError) throw new Exception(disco.Error);

                var response = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
                {
                    Address = disco.TokenEndpoint,
                    ClientId = "AuthServer",
                    ClientSecret = "04BF541804E7499B81EC17B67D19C881",
                    Scope = "AuthorServers"
                });

                if (response.IsError) throw new Exception(response.Error);
                var c = CallServiceAsync(response.AccessToken.ToString());
                return response;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        async Task CallServiceAsync(string token)
        {
            try
            {
                var baseAddress = addr + ":5005";
                var client = new HttpClient
                {
                    BaseAddress = new Uri(baseAddress)
                };

                client.SetBearerToken(token);
                var response = await client.GetStringAsync(baseAddress + "/auth/login/AuthUser/" + tbName.Text.ToString() + "/" + tbpass.Text.Trim());
                var res = JsonConvert.DeserializeObject<ApiRootModel>(response);
                if (res.IsSucceed)
                {
                    var jarray = (JObject)JsonConvert.DeserializeObject(res.Data.ToString());
                    tbCompany.Text = ((JObject)jarray["Claims"][1])["Value"].ToString();// jarray["UserName"].Value<string>();
                    var tenantid = jarray["TenantID"].Value<int>();
                    SysConfig.TenantId = Convert.ToInt32(tenantid);
                    ConfigHelper.UpdateAppConfig("tenantid", tenantid.ToString());
                }
                else
                {
                    MessageBox.Show(res.ErrorMessage, "提示");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("1.输入正确的数据库IP地址、端口、用户名和密码；" +
                "\n2.点击[连接本地数据库]，选择要连接的数据库；" +
                "\n3.输入服务端用户名和密码，点击[登陆获取企业]获取企业；" +
                "\n4.点击[保存配置]保存设置；" +
                "\n5.点击[访问测试]测试是否连接成功。", "怎么配置连接");
        }

        public void Add_type(string dbName, string server, string dk, string user, string pwd)
        {
            try
            {
                SysConfig.ClientIP = server;
                SysConfig.ClientPort = dk;
                SysConfig.ClientDbName = dbName;
                SysConfig.ClientUser = user;
                SysConfig.ClientPwd = pwd;


                var conStr = "Data Source='{0}';Port='{1}';User Id='{2}';Password='{3}';Database='{4}';pooling=true;character set=utf8;Connect Timeout=120";
                SysConfig.ConnectionStr = string.Format(conStr, server, dk, user, pwd, dbName);

                string pd = "select count(*) from information_schema.columns where table_name='order_no' and COLUMN_NAME='ADD_TYPE'";
                DataSet ds = null;
                DbHelperMySql.ExecuteQueryByConnstr(SysConfig.ConnectionStr, pd, out ds);
                if (Convert.ToInt32(ds.Tables[0].Rows[0][0]) != 0) return;

                string sql = @"ALTER TABLE `order_no`
ADD COLUMN `ADD_TYPE`  int DEFAULT 0 NULL COMMENT '0：默认新增值，1：已经上传';

ALTER TABLE `order_manage`
ADD COLUMN `ADD_TYPE`  int DEFAULT 0 NULL COMMENT '0：默认新增值，1：已经上传';

ALTER TABLE `order_manage_list`
ADD COLUMN `ADD_TYPE`  int DEFAULT 0 NULL COMMENT '0：默认新增值，1：已经上传';

ALTER TABLE `pp_big_lab_sup`
ADD COLUMN `ADD_TYPE`  int DEFAULT 0 NULL COMMENT '0：默认新增值，1：已经上传';

ALTER TABLE `pp_lab_lst_sup`
ADD COLUMN `ADD_TYPE`  int DEFAULT 0 NULL COMMENT '0：默认新增值，1：已经上传';

ALTER TABLE `ba_material` MODIFY COLUMN `MAT_TYPE_ID` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL;

update `order_no` set `ADD_TYPE`=0;
update `order_manage` set `ADD_TYPE`=0;
update `order_manage_list` set `ADD_TYPE`=0;
update `pp_big_lab_sup` set `ADD_TYPE`=0;
update `pp_lab_lst_sup` set `ADD_TYPE`=0;
                            ";
                ds = null;
                DbHelperMySql.ExecuteQueryByConnstr(SysConfig.ConnectionStr, sql, out ds);

            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "提示");
            }
        }

        private void cmb_DbName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
